package com.dmai.capacity.platform.user.service.impl;

import com.dmai.capacity.platform.common.constant.CodeEnum;
import com.dmai.capacity.platform.common.constant.CommonConstant;
import com.dmai.capacity.platform.common.dto.PageResult;
import com.dmai.capacity.platform.common.dto.PageResultData;
import com.dmai.capacity.platform.common.exception.BusinessException;
import com.dmai.capacity.platform.common.model.LoginAppUser;
import com.dmai.capacity.platform.constants.ConfigKeyConstant;
import com.dmai.capacity.platform.oauth.common.util.AuthUtils;
import com.dmai.capacity.platform.user.mapper.SysConfigDao;
import com.dmai.capacity.platform.user.model.SysConfig;
import com.dmai.capacity.platform.user.pojo.MailPO;
import com.dmai.capacity.platform.user.service.ISysConfigService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service
public class SysConfigServiceImpl implements ISysConfigService {

    @Autowired
    private SysConfigDao configDao;


    @Override
    public SysConfig findById(String id) {
        return configDao.findById(id);
    }

    @Override
    public SysConfig findByKey(String id) {
        SysConfig config = configDao.findByKey(id);
        return config;
    }

    @Override
    public List<MailPO> findEmails() {
        List<MailPO> mails = new ArrayList<>();
        List<SysConfig> list = configDao.findAll(new HashMap<>());
        TreeMap<String, List<SysConfig>> tempMap = list.stream().collect(Collectors.groupingBy(item -> item.getTenantId(), TreeMap::new, Collectors.toList()));
        for (Map.Entry entry_item : tempMap.entrySet()) {
            List<SysConfig> list_item = (List) entry_item.getValue();
            MailPO mail = new MailPO();
            mail.setTenantId(entry_item.getKey().toString());
            for (SysConfig item : list_item) {
                if (item.getConfKey().equals(ConfigKeyConstant.EMAIL_HOST)) {
                    mail.setHost(item.getConfValue());
                }
                if (item.getConfKey().equals(ConfigKeyConstant.EMAIL_PORT)) {
                    mail.setPort(Integer.valueOf(item.getConfValue()));
                }
                if (item.getConfKey().equals(ConfigKeyConstant.EMAIL_USERNAME)) {
                    mail.setUsername(item.getConfValue());
                }
                if (item.getConfKey().equals(ConfigKeyConstant.EMAIL_PASSWORD)) {
                    mail.setPassword(item.getConfValue());
                }
            }
            mails.add(mail);
        }
        return mails;
    }

    @Transactional
    @Override
    public int save(SysConfig config) {
        int i = 0;
        LoginAppUser loginAppUser = AuthUtils.getLoginAppUser();

        config.setUpdateTime(new Date());
        config.setUpdateUserid(loginAppUser.getId());
        config.setUpdateUsername(loginAppUser.getRealname());
        i = configDao.save(config);


        return i;
    }

    @Override
    public int update(SysConfig config) {
        int i = 0;
        LoginAppUser loginAppUser = AuthUtils.getLoginAppUser();
        SysConfig model = configDao.findById(config.getConfKey());
        if (model == null) {
            throw new BusinessException("找不到该配置项");
        }
        if (model != null) {
            config.setUpdateTime(new Date());
            config.setUpdateUserid(loginAppUser.getId());
            config.setUpdateUsername(loginAppUser.getRealname());
            i = configDao.updateByOps(config);
        }

        return i;
    }

    @Override
    public PageResult<SysConfig> pageAll(Map<String, Object> params) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, CommonConstant.PAGE_CURRENT) != null && MapUtils.getInteger(params, CommonConstant.PAGE_SIZE) != null)
            PageHelper.startPage(MapUtils.getInteger(params, CommonConstant.PAGE_CURRENT), MapUtils.getInteger(params, CommonConstant.PAGE_SIZE), true);

        List<SysConfig> list = configDao.findAll(params);
        PageInfo<SysConfig> pageInfo = new PageInfo(list);

        return PageResult.<SysConfig>builder().data(PageResultData.<SysConfig>builder().records(pageInfo.getList()).total(pageInfo.getTotal()).pages(pageInfo.getPages()).build()).code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();

    }

}
